<?php

class ServerHelper{
	
	//发送服务器API请求
	//参数1：API名称
	//参数2：请求参数
	//参数3：头信息
	public static function post($apiname_en,$data=[],$header=[]){
		$cfg = \think\Config::get('server');
		if(empty($cfg) || empty($cfg['api_host'])){
			__log('服务器API配置错误，配置名：server.api_host','api');
			return null;
		}
		$host = $cfg['api_host'];
		$api_dict = $cfg['api_dict'];
		
		//得到请求url
		if(substr($apiname_en,0,2) == '^/'){
			//直接是接口
			if(substr($apiname_en,-4) != '.tsl'){
				$apiname_en.= '.tsl';
			}
			$apiname_en = substr($apiname_en,1);//去掉开头的 ^
			$url = $host . $apiname_en;
		}else{
			//字典找接口
			if(!array_key_exists($apiname_en,$api_dict)){
				__log('服务器API接口名称选择错误:' . $apiname_en,'api');
				return null;
			}
			$url = $host . $api_dict[$apiname_en];
		}
		
		//签名
		$data['_time'] = date('Y-m-d H:i:s');
		$sign = self::sign($data,$cfg['api_secret']);
		$data['_sign'] = $sign;
		
		$response = null;
		try{
			$start_time = microtime(true);
			$response = \HttpHelper::post($url,$data,$header);
			$end_time = microtime(true);
			$run_time = ($end_time - $start_time) * 1000;
			__log($url . PHP_EOL . "耗时：{$run_time}]毫秒",'serverlog');
		}catch(Exception $e){
			__log('服务器API接口请求出错 + ' . $e->getMessage(),'api');
		}
		return $response;
	}
	
	//获取请求url
	public static function url($apiname_en){
		$cfg = \think\Config::get('server');
		if(empty($cfg) || empty($cfg['api_host'])){
			__log('服务器API配置错误，配置名：server.api_host','api');
			return '';
		}
		$host = $cfg['api_host'];
		$api_dict = $cfg['api_dict'];
		
		if(substr($apiname_en,0,2) == '^/'){
			//直接是接口
			if(substr($apiname_en,-4) != '.tsl'){
				$apiname_en.= '.tsl';
			}
			$apiname_en = substr($apiname_en,1);//去掉开头的 ^
			$url = $host . $apiname_en;
		}else{
			//字典找接口
			if(!array_key_exists($apiname_en,$api_dict)){
				__log('服务器API接口名称选择错误','api');
				return null;
			}
			$url = $host . $api_dict[$apiname_en];
		}
		
		return $url;
	}
	
	private static function sign($data,$secret){
		ksort($data);
		$query = http_build_query($data);
		return md5($query . $secret);
	}
	
	//获取OSS配置
	public static function GetOSSConfig(){
		$response = self::post('GetAliyunOSSInfo');
		$data = json_decode($response,true);
		return $data;
		if(empty($data['flag'])){
			return null;
		}
		return $data['data'];
	}
	
	//获取微信配置(登陆配置、支付配置)
	public static function GetWeChatConfig(){
		$response = self::post('GetWeChatConfig');
		return json_decode($response,true);
	}
	
}